/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.aplink.generic.autosync;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncStatusObserver;
import android.os.Bundle;

import com.aplink.generic.GenericApplication;
import com.aplink.generic.cache.MasterConfigManager;
import com.aplink.generic.pojo.MasterConfig;
import com.aplink.generic.sharepreference.GenericSharePreference;

public class SyncUtils {
	private static SyncUtils sInstance = null;

	public static SyncUtils getInstance() {
		if (SyncUtils.sInstance == null) {
			SyncUtils.sInstance = new SyncUtils();
		}
		return sInstance;
	}

	private String mAuthority = null;
	private MasterConfig mMasterConfig;

	private Object mSyncObserverHandle;

	private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {

		@Override
		public void onStatusChanged(final int which) {

		}
	};

	private SyncUtils() {
		mMasterConfig = MasterConfigManager.getInstance().get(
		        GenericSharePreference.getInstance().getMasterConfigFileID());
		if (mMasterConfig.getAutoSync() != null) {
			mAuthority = mMasterConfig.getAutoSync().getAuthorities();
		}
	}

	public void CreateSyncAccount() {
		if (this.mMasterConfig.getAutoSync() != null) {
			boolean newAccount = false;
			Context context = GenericApplication.getInstance()
			        .getApplicationContext();
			boolean setupComplete = GenericSharePreference.getInstance()
			        .isSetUpAccountComplete();
			Account account = GenericAccountService
			        .GetAccount(this.mMasterConfig);
			AccountManager accountManager = (AccountManager) context
			        .getSystemService(Context.ACCOUNT_SERVICE);
			if (accountManager.addAccountExplicitly(account, null, null)) {
				ContentResolver.setIsSyncable(account, this.mAuthority, 1);
				ContentResolver.setSyncAutomatically(account, this.mAuthority,
				        true);
				ContentResolver.addPeriodicSync(account, this.mAuthority,
				        new Bundle(), this.mMasterConfig.getAutoSync()
				                .getInterval());
				newAccount = true;
			}
			if (newAccount || !setupComplete) {
				GenericSharePreference.getInstance().setUpAccountComplete(true);
			}
		}
	}

	public void disableAutoSync() {
		if (GenericSharePreference.getInstance().isSetUpAccountComplete()) {
			if (this.mSyncObserverHandle != null) {
				ContentResolver
				        .removeStatusChangeListener(this.mSyncObserverHandle);
				this.mSyncObserverHandle = null;
			}
		}
	}

	public void enableAutoSync() {
		final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING
		        | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
		this.mSyncObserverHandle = ContentResolver.addStatusChangeListener(
		        mask, this.mSyncStatusObserver);
	}

	public void startSynchronize() {
		final Bundle b = new Bundle();
		b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
		b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
		ContentResolver.requestSync(
		        GenericAccountService.GetAccount(this.mMasterConfig),
		        this.mAuthority, b);
	}
}
